package secret.santa.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class UserPanel extends Composite implements ClickHandler, KeyUpHandler  
{

	private static UserPanelUiBinder uiBinder = GWT
			.create(UserPanelUiBinder.class);

	interface UserPanelUiBinder extends UiBinder<Widget, UserPanel> {
	}
	
	private boolean userEdit;
	private boolean userDeleting;
	
	private CS_User[] userData;
	
	private IndexCheckBox[] userSelect;
	
	private int indexUserEdit;
	
	private Secret_Santa santa;
	@UiField
	Button makeCoupleButton;
	@UiField
	Button deleteButton;
	@UiField
	FlexTable userTable;
	
	private PasswordTextBox passwordTextBox;
	private TextBox emailTextBox;
	private TextBox fullNameTextBox;
	private Button userAddButton;
	private Button userEditButton;
	private Button userEditCancelButton;
	private TextBox userNameTextBox;
	private Label userNameLabel;
	private Label passwordLabel;
	private Label emailLabel;
	private Label fullNameLabel;
	private Label partnerLabel;
	
	public UserPanel(Secret_Santa s) {
		initWidget(uiBinder.createAndBindUi(this));
		santa = s;
		userEdit = false;
		userDeleting = false;
		indexUserEdit = -1;
		initChildWidgets();
		addHandlers();
	}

	private void addHandlers() 
	{
		userNameTextBox.addKeyUpHandler(this);
		passwordTextBox.addKeyUpHandler(this);
		fullNameTextBox.addKeyUpHandler(this);
		emailTextBox.addKeyUpHandler(this);
		userAddButton.addClickHandler(this);
		userEditCancelButton.addClickHandler(this);
		
	}

	private void initChildWidgets() 
	{
		userNameLabel = new Label("Login");
		
		passwordLabel = new Label("Password");
		
		fullNameLabel = new Label("Full Name");
		
		emailLabel = new Label("Email");
		
		partnerLabel = new Label("Partner");
		
		userNameTextBox = new TextBox();
		
		passwordTextBox = new PasswordTextBox();
		
		fullNameTextBox = new TextBox();
		
		emailTextBox = new TextBox();

		userAddButton = new Button("Add User");
		
		userEditButton = new Button("Edit User");
		
		userEditCancelButton = new Button("Cancel");
	}

	@UiHandler("makeCoupleButton")
	void makeCouple(ClickEvent e)
	{
		int size = userSelect.length;
		
		int indices[] = new int[2];
		
		int found = 0;
	
		for(int i = 0; i < size; i++)
		{
			if(userSelect[i].getValue())	
			{
				indices[found]= i;
				found++;
			}
			
			if(found > 2)
			{
				Window.alert("Threesomes or more are not allowed, select 2 users and click Make Couple.");
				return;
			}
		}
		if(found != 2)
		{
			Window.alert("Select 2 users and click Make Couple.");
			return;
		}
		santa.makeCouple(userData[indices[0]].encodedKey, userData[indices[1]].encodedKey);
		
		userSelect[indices[0]].setValue(false);
		userSelect[indices[1]].setValue(false);
	}
	@UiHandler("deleteButton")
	void deleteSelectedUsers(ClickEvent e)
	{
		if(userDeleting)
			return;
		userDeleting = true;
		String [] keys = getSelectedUserKeys();
		
		if(keys.length == 0)
		{
			Window.alert("Select at least one user to delete.");
			userDeleting = false;
			return;
		}
		santa.deleteUsers(keys);	
		clearSelection();
	}
	
	public CS_User[] getUserdata()
	{
		return userData;
	}
	private void cancelUserEdit() 
	{
		santa.getUsers();
		userEdit = false;
		indexUserEdit = 0;
		
		userTable.remove(userEditButton);
		userTable.remove(userEditCancelButton);
		
		userTable.setWidget(1,0,userNameTextBox);

		userTable.setWidget(1,1,passwordTextBox);
		
		userTable.setWidget(1,2,fullNameTextBox);
		
		userTable.setWidget(1,3, emailTextBox);

		userTable.setWidget(1,4, userAddButton);
		
		userNameTextBox.setText("");
		passwordTextBox.setText("");
		fullNameTextBox.setText("");
		emailTextBox.setText("");
			
	}
	
	
	private void editUser(int index) 
	{
		
		userEdit = true;
		indexUserEdit = index + 2;
		
		String username = userData[index].username;
		String password = userData[index].password;
		String fullName = userData[index].fullName;
		String email = userData[index].email;
		userTable.removeCells(index, 0, 7);
		
		userTable.setWidget(indexUserEdit, 1, userNameTextBox);
		userTable.setWidget(indexUserEdit, 2, passwordTextBox);
		userTable.setWidget(indexUserEdit, 3, fullNameTextBox);
		userTable.setWidget(indexUserEdit, 4, emailTextBox);
		userTable.setWidget(indexUserEdit, 5, userEditButton);
		userTable.setWidget(indexUserEdit, 6, userEditCancelButton);
		
		userNameTextBox.setText(username);
		passwordTextBox.setText(password);
		fullNameTextBox.setText(fullName);
		emailTextBox.setText(email);
		
	}
	
	public void userDeleted()
	{
		userDeleting = false;
	}
	
	public void userEdited()
	{
		userEdit = false;
		indexUserEdit = -1;
	}
	
	@Override
	public void onClick(ClickEvent event) 
	{
		if(event.getSource() == userAddButton)
			addUser();
		else if(event.getSource().getClass() == EditButton.class)
			editUser(((EditButton)event.getSource()).getIndex());
		else if(event.getSource() == userEditCancelButton)
			cancelUserEdit();		
	}
	private String [] getSelectedUserKeys()
	{
		int size = userSelect.length;
		String keys[] = new String[size];
				
		int found = 0;
	
		for(int i = 0; i < size; i++)
		{
			if(userSelect[i].getValue())
			{
				keys[found]= userData[i].encodedKey;
				found++;
			}
		}
		//String []ret = Arrays.copyOf(keys, found);
		//TODO: make more efficient (jsarrays)
		String [] ret = new String[found];
		for(int i = 0; i < found; i++)
			ret[i] = keys[i];

		return ret;
		
	}
	private void clearSelection() 
	{
		int size = userSelect.length;
		for(int i = 0; i < size; i++)
			userSelect[i].setValue(false);
	}
	private int[] getSelectedUserIndices()
	{
		int size = userSelect.length;
		int indices[] = new int[size];
				
		int found = 0;
	
		for(int i = 0; i < size; i++)
		{
			if(userSelect[i].getValue())
			{
				indices[found]= i;
				found++;
			}
		}
		//TODO: make more efficient (jsarrays)
		int [] ret = new int[found];
		for(int i = 0; i < found; i++)
			ret[i] = indices[i];

		return ret;
	}
	
	@Override
	public void onKeyUp(KeyUpEvent event) 
	{
		if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) 
		{
			if(event.getSource() == userNameTextBox || event.getSource() == passwordTextBox ||
					event.getSource() == emailTextBox || event.getSource() == fullNameTextBox )
			{
				if(userEdit)
					editUser();
				else
					addUser();
			}
		}
		
	}
	
	private void editUser() 
	{

		String name = userNameTextBox.getText();
		String password = passwordTextBox.getText();
		String email = emailTextBox.getText();
		String fullName = fullNameTextBox.getText();
	
		if(name.length() == 0 || name.length() == 0)
			Window.alert("One of the required fields is empty.");
		else
			santa.editUser(userData[indexUserEdit].encodedKey, name, password, fullName, email);
		userNameTextBox.setText("");
		passwordTextBox.setText("");
		emailTextBox.setText("");
		fullNameTextBox.setText("");
		
	}
	
	private void addUser() 
	{
		String name = userNameTextBox.getText();
		String password = passwordTextBox.getText();
		String email = emailTextBox.getText();
		String fullName = fullNameTextBox.getText();
	
		if(name.length() == 0 || name.length() == 0)
			Window.alert("One of the required fields is empty.");
		else
			santa.addUser(name, password, fullName, email);
		userNameTextBox.setText("");
		passwordTextBox.setText("");
		emailTextBox.setText("");
		fullNameTextBox.setText("");
		
	}
	
	public void displayUsers(CS_User[] u) 
	{
		int size = u.length;
		
		userData = u;
		
		userTable.clear();
		userSelect = new IndexCheckBox[size];
		
		initUserHeader();
		int i;
		for(i = 0; i < size; i++)
		{
			userSelect[i] = new IndexCheckBox();
			EditButton edit = new EditButton();
			edit.setIndex(i);
			edit.addClickHandler(this);
			userSelect[i].setIndex(i);
			userTable.setWidget(i+2,0,userSelect[i]);
			userTable.setWidget(i+2,1,new Label(u[i].username));
			userTable.setWidget(i+2,2,new Label(u[i].password));
			userTable.setWidget(i+2,3,new Label(u[i].fullName));
			userTable.setWidget(i+2,4,new Label(u[i].email));
			userTable.setWidget(i+2,5,new Label(u[i].partner));
			userTable.setWidget(i+2,7,edit);	
		}
		
	}
	
	private void initUserHeader() 
	{
		userTable.setWidget(0, 1, userNameLabel);
		userTable.setWidget(0, 2, passwordLabel);
		userTable.setWidget(0, 3, fullNameLabel);
		userTable.setWidget(0, 4, emailLabel);
		userTable.setWidget(0, 5, partnerLabel);
		userTable.setWidget(1, 1, userNameTextBox);
		userTable.setWidget(1, 2, passwordTextBox);
		userTable.setWidget(1, 3, fullNameTextBox);
		userTable.setWidget(1, 4, emailTextBox);
		userTable.setWidget(1, 5, userAddButton);
	}
	public CS_User[] getUserData() 
	{
		return userData;
	}

}
